package com.mongo.jdbc.core;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 /**
  * 
  * @author:binggong
  * @createtime:2019年11月12日 下午8:53:26
  * @version:V.0.1
  * @tag: 识别出大括号中的信息
  *
  */
public class ExtractMessage {
 
	public static void main(String[] args) {
		
		String msg = "{'category_name':'笔记本','isits': { $gt: 3 }}, {'category_name': 1, 'task_id': 1 }";
		List<String> list = extractMessage(msg);
		for (int i = 0; i < list.size(); i++) {
			System.out.println(i+"-->"+list.get(i));
		}
	}
	
	/**
	 * 提取大括号中内容，忽略中括号中的中括号
	 * @param msg
	 * @return
	 */
	public static List<String> extractMessage(String msg) {
 
		List<String> list = new ArrayList<String>();
		int start = 0;
		int startFlag = 0;
		int endFlag = 0;
		for (int i = 0; i < msg.length(); i++) {
			if (msg.charAt(i) == '{') {
				startFlag++;
				if (startFlag == endFlag + 1) {
					start = i;
				}
			} else if (msg.charAt(i) == '}') {
				endFlag++;
				if (endFlag == startFlag) {
					list.add(msg.substring(start , i+ 1));
				}
			}
		}
		return list;
	}
	
	
	/**
	 *  根据分号 ';' 对脚本进行分割 ；实现多脚本执行时候，脚本分割
	 * @param script
	 * @return
	 */
	public static List<String> getMoreScript(String script) {
		script = script.replace(System.lineSeparator(), " ");
		List<String> list = new ArrayList<String>();
		boolean falg =false;
		boolean falg2 = false;
		int startIndex = 0;
		boolean isMore = false;
		for (int i = 0; i < script.length(); i++) {
		
			if (script.charAt(i) == '"') {
				if (falg) {
					falg = false;
				}else {
					falg = true;
				}
			}
			
			if (script.charAt(i) == '\'') {
				if (falg2) {
					falg2 = false;
				}else {
					falg2 = true;
				}
			}
			
			
			if (!falg&&!falg2) {
				if (script.charAt(i) == ';') {
					list.add(script.substring(startIndex,i).trim());
					startIndex = i+1;
					isMore = true;
				}
			}
			
			
		}
		if (isMore) {
			String data = script.substring(startIndex);
			if (!data.trim().equals("")) {
				list.add(data.trim());
			}
		}
		if (list.size() == 0) {
			list.add(script);
		}
		
		return list;
	} 
	
	
	
	/**
	 *     判断脚本中是否含有script标签
	 * @param script 
	 * @return  true:是mybatis的脚本，false不是mybatis脚本
	 */
	public static boolean isCheckMyBatisScript(String script ) {
		
		boolean isMyBatisScript = false;
		
		boolean falg =false;
		boolean falg2 = false;
		for (int i = 0; i < script.length(); i++) {
		
			if (script.charAt(i) == '"') {
				if (falg) {
					falg = false;
				}else {
					falg = true;
				}
			}
			
			if (script.charAt(i) == '\'') {
				if (falg2) {
					falg2 = false;
				}else {
					falg2 = true;
				}
			}
			
			
			if (!falg&&!falg2) {
				if (script.charAt(i) == '<') {
					isMyBatisScript = true;
					break;
				}
			}
		}
		
		return isMyBatisScript;
	}
	
 
}

